package org.rambadger.command.resource;

import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.mongodb.BasicDBObject;
import com.yammer.dropwizard.auth.Auth;
import com.yammer.dropwizard.jersey.params.IntParam;
import org.mongojack.DBCursor;
import org.mongojack.JacksonDBCollection;
import org.rambadger.command.auth.AuthUser;
import org.rambadger.command.axon.JCollection;
import org.rambadger.command.providers.Pagination;
import org.rambadger.command.representation.Platform;
import org.rambadger.command.view.PlatformView;
import org.rambadger.command.view.PlatformsView;

import javax.annotation.Nullable;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;

@Path("/platforms/")
public class ViewPlatformsResource {

    @JCollection(type=Platform.class)

    private JacksonDBCollection<Platform, String> platforms = null;

    @GET
    @Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_JSON})

    public Object getPlatformList(@Auth(required = true) AuthUser user, @QueryParam("page") @Min(1) @DefaultValue("1") IntParam page,
                              @QueryParam("limit") @DefaultValue("20") @Min(1) @Max(100) IntParam platformsPerPage) {

        DBCursor<Platform> found = platforms.find().sort(new BasicDBObject("_id",1));

        int platformsTotal = platforms.find().count();
        int pagesTotal = (int) Math.ceil((double)platformsTotal / (double)platformsPerPage.get());
        
        found.limit(platformsPerPage.get()).skip((page.get()-1)*platformsPerPage.get());

        List<PlatformView> platformsFound;
        platformsFound = FluentIterable.from(found).transform(new Function<Platform, PlatformView>() {
            @Nullable
            @Override
            public PlatformView apply(@Nullable Platform input) {
                return new PlatformView(null, input);
            }
        }).toList();
        found.close();

        if (pagesTotal > 1)
            return new Pagination(page.get(), platformsPerPage.get());

        else
            return new PlatformsView(user, platformsFound);

    }

}

